<template>
  <div class="app-container">
    <comm-search v-if="showSearch" @search="initList()" :query-param="queryParam">
      <template #left>
        <el-form-item prop="blurry">
          <el-input v-model="queryParam.blurry" clearable placeholder="输入名称或者描述搜索"
                    @keyup.enter.native="initList()"/>
        </el-form-item>

      </template>
    </comm-search>
    <comm-tool :selections="selections" v-model:show-search="showSearch" :del-url="baseUrl" @toAdd="toAdd({})"
               @edit="toAdd(selections[0])" @refresh="initList()" :permission="permission"/>
    <comm-edit-dialog v-model:dialog-show="editDialogShow" :url="baseUrl" title="角色" @refresh="initList()" @save="toSave">
      <template #content>
        <el-form ref="form" :model="formData" :rules="rules">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="formData.name"/>
          </el-form-item>
          <el-form-item label="描述信息" prop="description">
            <el-input v-model="formData.description" rows="5" type="textarea"/>
          </el-form-item>
        </el-form>
      </template>
    </comm-edit-dialog>
    <el-row :gutter="15">
      <!--角色管理-->
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="17" style="margin-bottom: 10px">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">角色列表</span>
          </div>
          <el-table :loading="loading" :data="dataList" @selectionChange="selectionChange"
                    @currentChange="handleCurrentChange" highlight-current-row>
            <el-table-column type="selection" width="55"/>
            <el-table-column prop="name" label="名称"/>
            <el-table-column :show-overflow-tooltip="true" prop="description" label="描述"/>
            <el-table-column :show-overflow-tooltip="true" prop="createTime" label="创建日期"/>
            <el-table-column label="操作" width="130px" align="center" fixed="right">
              <template #default="scope">
                <comm-operation :data="scope.row" :url="baseUrl" :disabled-del="scope.row.id==='1'"
                                @edit="toEdit(scope.row)" @refresh="initList()" :permission="permission"/>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-model:page="queryParam.page" v-model:limit="queryParam.size" :total="total"
                      @change="initList()"/>
        </el-card>
      </el-col>
      <!-- 菜单授权 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="7">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配菜单" placement="top">
              <span class="role-span">菜单分配</span>
            </el-tooltip>
            <el-button
                :loading="menuLoading"
                style="float: right; padding: 6px 9px"
                type="primary"
                @click="saveMenu"
            >保存
            </el-button>
          </div>
          <el-tree
              ref="menu"
              :data="menus"
              :default-checked-keys="menuIds"
              :props="defaultProps"
              check-strictly
              accordion
              show-checkbox
              node-key="id"
              @check="menuChange"
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>


<script setup>
import {ref, toRefs, reactive, getCurrentInstance} from 'vue'
import Pagination from '@/components/Pagination'
import mixins from "@/mixins/mixins";
import CommSearch from "@/components/Comm/CommSearch.vue";
import CommTool from "@/components/Comm/CommTool.vue";
import CommEditDialog from "@/components/Comm/CommEditDialog.vue";
import CommOperation from "@/components/Comm/CommOperation.vue";
import {get, put} from "@/utils/request";
import { ElMessage } from 'element-plus'

const  permission={edit: ['roles:edit'],del: ['roles:del'],add:['roles:add']}
const pageData = reactive({
  rules: {
    name: [
      {required: true, message: '请输入名称', trigger: 'blur'}
    ],
    permission: [
      {required: true, message: '请输入权限', trigger: 'blur'}
    ]
  },
  menuIds: []
})

const {initList, total, dataList, data, selectionChange, toAdd,toEdit, toSave} = mixins()
const {queryParam, loading, saveLoading, selections, showSearch, editDialogShow, formData, baseUrl} = toRefs(data)

const {rules,menuIds} = toRefs(pageData)
const isEdit = ref(false)
const roles = ref([])
const {proxy} = getCurrentInstance();
const menus = ref([])
const  curRow=ref({})
const  menuLoading=ref(false)
const defaultProps = {
  children: 'children', label: function (data, node) {
    return data.meta.title
  }
}

baseUrl.value = '/roles'

function initMenus() {
  get('/menus/all?hasBtn=true').then(res => {
    menus.value = res
  })
}

function  saveMenu(){
    let keys=proxy.$refs['menu'].getCheckedKeys()
    keys=keys.concat(proxy.$refs['menu'].getHalfCheckedKeys())
     put('/roles/menu',{id:curRow.value.id,menus:keys}).then(res=>{
       ElMessage('保存成功')
     })
}

function handleCurrentChange(row){
    if(row){
      curRow.value=row
      proxy.$refs['menu'].setCheckedKeys([])
      menuIds.value=row.menus
    }

}
function getChild(id) {
  return get('menus/child?id=' + id)
}
function menuChange(menu) {
  // 获取该节点的所有子节点，id 包含自身
  getChild(menu.id).then(childIds => {
    // 判断是否在 menuIds 中，如果存在则删除，否则添加
    if (menuIds.value.indexOf(menu.id) !== -1) {
      for (let i = 0; i < childIds.length; i++) {
        const index = menuIds.value.indexOf(childIds[i])
        if (index !== -1) {
          menuIds.value.splice(index, 1)
        }
      }
    } else {
      for (let i = 0; i < childIds.length; i++) {
        const index = menuIds.value.indexOf(childIds[i])
        if (index === -1) {
          menuIds.value.push(childIds[i])
        }
      }
    }
    proxy.$refs['menu'].setCheckedKeys(menuIds.value)
  })
}
initList()
initMenus()
</script>


<style rel="stylesheet/scss" lang="scss">
.role-span {
  font-weight: bold;
  color: #303133;
  font-size: 15px;
}
</style>
